<?php


/* 定义like语句转换为in语句的条件 */
define('MAX_ID_NUM_OF_IN', 10000); // IN语句的最大ID数
define('MAX_HIT_RATE', 0.05); // 最大命中率（满足条件的记录数除以总记录数）
define('MAX_STAT_PRICE', 10000); // 最大统计价格
define('PRICE_INTERVAL_NUM', 5); // 价格区间个数
define('MIN_STAT_STEP', 50); // 价格区间最小间隔
define('NUM_PER_PAGE', 16); // 每页显示数量
define('ENABLE_SEARCH_CACHE', true); // 启用商品搜索缓存
define('SEARCH_CACHE_TTL', 3600); // 商品搜索缓存时间

class SearchApp extends MallbaseApp {
	/* 搜索商品 */
	function index() {
		// 查询参数
		$param = $this->_get_query_param();
		//        if (isset($param['cate_id']) && $param['layer'] === false)
		//        {
		//            $this->show_warning('no_such_category');
		//            return;
		//        }
		$this->searchgoods($param);
	}

	function searchbar() { //搜索框
		$param = $this->_get_query_param();
		if (preg_match("/[^\d-., ]/", $param['keyword'][0])) { //不是数字
			$this->assign('search_keyword', $param['keyword'][0]);
		} else {
            $param['numtype']="nonum";
		}
		$this->searchgoods($param);
	}

	function hotselect() { //热门搜索
		$param = $this->_get_query_param();
		$param["hottype"] = "hot";
		$this->assign('search_keyword', $param['keyword'][0]);
		$this->searchgoods($param);
	}

	function searchgoods($param = array ()) {
		$keyvar;
		$keyvalue;
		$i = 0;
		foreach ($param as $key => $value) {
			$keyvar = $key;
			$keyvalue = $value;
			$i++;
		}
		if ($keyvar == "brand" && $i == 1) {
			$brand_mod = & m('brand');
			$brandid = $brand_mod->get_brandid($keyvalue);
			$this->assign('brand_id', $brandid[0]['brand_id']);
		} else {
			if (isset ($param['hottype'])) {
				$scate_mod = & m('scategory');
				$scateid = $scate_mod->get_cateid($param['keyword'][0]);
				$this->assign('cate_id', $scateid[0]['cate_id']);
				$this->assign('keyword', $param['keyword'][0]);
				$this->assign('filters', $this->_get_filter($param));
			} else {
				list ($pr1, $pr2) = explode("-", $param['keyword'][0]);
				if (preg_match("/[^\d-., ]/", $pr1)) { //不是数字
					/* 筛选条件 */
					$this->assign('keyword', $param['keyword'][0]);
					$this->assign('filters', $this->_get_filter($param));
				} else {
					/* 筛选条件 */
					$this->assign('keyword', $param['keyword'][0]);
					$this->assign('filters', $this->_get_filter($param));
					$this->assign('price_id', $param['keyword'][0]);
				}
			}
		}

		/* 按分类、品牌、地区、价格区间统计商品数量 */
		$stats = $this->_get_group_by_info($param, ENABLE_SEARCH_CACHE);

		$this->assign('categories', $stats['by_category']);
		$this->assign('category_count', count($stats['by_category']));

		$this->assign('brands', $stats['by_brand']);
		$this->assign('brand_count', count($stats['by_brand']));

		$this->assign('price_intervals', $stats['by_price']);

		$this->assign('regions', $stats['by_region']);
		$this->assign('region_count', count($stats['by_region']));

		/* 排序 */
		$orders = $this->_get_orders();
		$this->assign('orders', $orders);

		/* 分页信息 */
		$page = $this->_get_page(NUM_PER_PAGE);
		$page['item_count'] = $stats['total_count'];
		$this->_format_page($page);
		$this->assign('page_info', $page);

		/* 商品列表 */
		/*
		 * $sgrade_mod = & m('sgrade');
		$sgrades = $sgrade_mod->get_options();
		$conditions = $this->_get_goods_conditions($param);
		 */
		$goods_mod = & m('goods');
		//		$goods_list = $goods_mod->get_list(array (
		//			'conditions' => $conditions,
		//			'order' => isset ($_GET['order']
		//		) && isset ($orders[$_GET['order']]) ? $_GET['order'] : '', 'limit' => $page['limit'],), $param);
		 if(!empty($param['cate_id'])){
		 	$goods_list = $goods_mod->get_cateinfo(array (
				'order' => $_GET['order'],
				'limit' => $page['limit']
			 ), $param);
			}else{
				$goods_list = $goods_mod->get_priceinfo(array (
				'order' => $_GET['order'],
				'limit' => $page['limit']
			 ), $param);
		 }
		foreach ($goods_list as $key => $goods) {
			$step = intval(Conf :: get('upgrade_required'));
			$step < 1 && $step = 5;
			$store_mod = & m('store');
			$goods_list[$key]['credit_image'] = $this->_view->res_base . '/images/' . $store_mod->compute_credit($goods['credit_value'], $step);
			empty ($goods['default_image']) && $goods_list[$key]['default_image'] = Conf :: get('default_goods_image');
			$goods_list[$key]['grade_name'] = $sgrades[$goods['sgrade']];
		}
		$this->assign('goods_list', $goods_list);

		/* 商品展示方式 */
		$display_mode = ecm_getcookie('goodsDisplayMode');
		if (empty ($display_mode) || !in_array($display_mode, array (
				'list',
				'squares'
			))) {
			$display_mode = 'squares'; // 默认格子方式
		}
		$this->assign('display_mode', $display_mode);

		/* 取得导航 */
		$this->assign('navs', $this->_get_navs());

		/* 当前位置 */
		$cate_id = isset ($param['cate_id']) ? $param['cate_id'] : 0;
		$this->_curlocal($this->_get_goods_curlocal($cate_id));

		/* 配置seo信息 */
		$this->_config_seo($this->_get_seo_info('goods', $cate_id));
		$this->display('search.goods.html');
	}

	function goods() {
		//接受4个参数
		$cate_id = $_GET['cate_id'];
		$brand_id = $_GET['brand_id'];
		$price_id = $_GET['price_id'];
		$region_id = $_GET['region_id'];
		$keyword = $_GET['keyword'];
		$this->assign('cate_id', $cate_id);
		$this->assign('brand_id', $brand_id);
		$this->assign('price_id', $price_id);
		$this->assign('region_id', $region_id);
		$array = array (
			$cate_id,
			$brand_id,
			$price_id,
			$region_id,
			$keyword
		);

		$stats = $this->_get_goods_group_by_info($array, ENABLE_SEARCH_CACHE);
		/* 查询传入参数的名称 */
		$keywordstats = $this->_get_keyword_group_by_info($array);
		$cate_name = $keywordstats['catearray'][0]['cate_name'];
		$brand_name = $keywordstats['brandarray'][0]['brand_name'];
		$price_name = $keywordstats['pricearray'][0]['price_name'];
		$region_name = $keywordstats['regionarray'][0]['region_name'];
		$keyword_name = $keywordstats['keywordarray'][0]['goods_name'];
		if (!empty ($cate_name) || !empty ($brand_name) || !empty ($price_name) || !empty ($region_name) || !empty ($keyword_name)) {
			$this->assign('showdiv', 1);
		}
		/*关键字*/
		$this->assign('keyword', $keyword);
		$this->assign('cate_name', $cate_name);
		$this->assign('brand_name', $brand_name);
		$this->assign('price_name', $price_name);
		$this->assign('region_name', $region_name);
		$this->assign('keyword_name', $keyword);
		/* 按分类、品牌、地区、价格区间统计商品数量 */
		$this->assign('categories', $stats['by_category']);
		$this->assign('category_count', count($stats['by_category']));

		$this->assign('brands', $stats['by_brand']);
		$this->assign('brand_count', count($stats['by_brand']));

		$this->assign('price_intervals', $stats['by_price']);

		$this->assign('regions', $stats['by_region']);
		$this->assign('region_count', count($stats['by_region']));
		/* 排序 */
		$orders = $this->_get_orders();
		$this->assign('orders', $orders);

		/* 分页信息 */
		$page = $this->_get_page(NUM_PER_PAGE);
		$page['item_count'] = $stats['total_count'];
		$this->_format_page($page);
		$this->assign('page_info', $page);
		/* 商品列表 */
		$goods_mod = & m('goods');
		$goods_list = $goods_mod->get_goods_info(array (
			'order' => $_GET['order'],
			'limit' => $page['limit']
		), $array);
		foreach ($goods_list as $key => $goods) {
			$step = intval(Conf :: get('upgrade_required'));
			$step < 1 && $step = 5;
			$store_mod = & m('store');
			$goods_list[$key]['credit_image'] = $this->_view->res_base . '/images/' . $store_mod->compute_credit($goods['credit_value'], $step);
			empty ($goods['default_image']) && $goods_list[$key]['default_image'] = Conf :: get('default_goods_image');
			$goods_list[$key]['grade_name'] = $sgrades[$goods['sgrade']];
		}
		$this->assign('goods_list', $goods_list);
		$this->assign('goods_count', count($goods_list));
		/* 商品展示方式 */
		$display_mode = ecm_getcookie('goodsDisplayMode');
		if (empty ($display_mode) || !in_array($display_mode, array (
				'list',
				'squares'
			))) {
			$display_mode = 'squares'; // 默认格子方式
		}
		$this->assign('display_mode', $display_mode);

		/* 取得导航 */
		$this->assign('navs', $this->_get_navs());

		/* 当前位置 */
		$this->_curlocal($this->_get_store_curlocal($cate_id));
		/* 配置seo信息 */
		//        $this->_config_seo($this->_get_seo_info('goods', $cate_id));
		$this->display('search.goods.html');
	}

	/* 搜索店铺 */
	function store() {
		/* 取得导航 */
		$this->assign('navs', $this->_get_navs());

		$cate_id = $_GET['cate_id'];
		$region_id = $_GET['region_id'];
		$keyword = $_GET['keyword'];
		if(!empty($keyword)){
          $this->assign('store_keyword', $keyword);
          $this->assign('search_keyword', $keyword);
          $this->assign('showdiv', 1);
		}
		$this->assign('cate_id', $cate_id);
		$this->assign('region_id', $region_id);
		$array = array (
			$cate_id,
			$region_id,
			$keyword
		);
		/*
		 * $cate_ids=array();
		$condition_id='';
		if ($cate_id > 0)
		{
		    $scategory_mod =& m('scategory');
		    $cate_ids = $scategory_mod->get_descendant($cate_id);
		}

		/* 店铺分类检索条件
		$condition_id=implode(',',$cate_ids);//477
		if(empty($_GET['cate_id'])){ //地区分类
			$condition_id && $condition_id = ' AND region_id IN(' . $condition_id . ')';
		}else{ //店铺分类
			$condition_id && $condition_id = ' AND cate_id IN(' . $condition_id . ')';
		}
		 */

		/* 查询传入参数的名称 */
		$storestats = $this->_get_store_group_by_info($array);
		$cate_name = $storestats['catearray'][0]['cate_name'];
		$region_name = $storestats['regionarray'][0]['region_name'];
		if (!empty ($cate_name) || !empty ($region_name) || !empty ($keyword_name)) {
			$this->assign('showdiv', 1);
		}
		/*关键字*/
		$this->assign('keyword', $keyword);
		$this->assign('cate_name', $cate_name);
		$this->assign('region_name', $region_name);
		/* 其他检索条件 */
		$conditions = $this->_get_query_conditions(array (
				array (//店铺名称
				'field' => 'store_name',
				'equal' => 'LIKE',
				'assoc' => 'AND',
				'name' => 'keyword',
				'type' => 'string',


			),
				array (//地区名称
				'field' => 'region_name',
				'equal' => 'LIKE',
				'assoc' => 'AND',
				'name' => 'region_name',
				'type' => 'string',


			),
				array (//地区id
				'field' => 'region_id',
				'equal' => '=',
				'assoc' => 'AND',
				'name' => 'region_id',
				'type' => 'string',


			),
				array (//商家用户名
				'field' => 'user_name',
				'equal' => 'LIKE',
				'assoc' => 'AND',
				'name' => 'user_name',
				'type' => 'string',
			),
		));

		$model_store = & m('store');
		$regions = $model_store->list_regions();
		$page = $this->_get_page(10); //获取分页信息

		/*
		 * $stores = $model_store->find(array(
		    'conditions'  => 'state = ' . STORE_OPEN . $condition_id . $conditions,
		    'limit'   =>$page['limit'],
		    'order'   => empty($_GET['order']) || !in_array($_GET['order'], array('credit_value desc')) ? 'sort_order' : $_GET['order'],
		    'join'    => 'belongs_to_user,has_scategory',

		    'count'   => true   //允许统计
		));
		 */
		$stores = $model_store->findstore(array (
		    'conditions'  => $condition_id . $conditions,
			'order' => $_GET['order'],
			'limit' => $page['limit']
		), $array);
		$model_goods = & m('goods');

		foreach ($stores as $key => $store) {
			//店铺logo
			empty ($store['store_logo']) && $stores[$key]['store_logo'] = Conf :: get('default_store_logo');

			//商品数量
			$stores[$key]['goods_count'] = $model_goods->get_count_of_store($store['store_id']);

			//等级图片
			$step = intval(Conf :: get('upgrade_required'));
			$step < 1 && $step = 5;
			$stores[$key]['credit_image'] = $this->_view->res_base . '/images/' . $model_store->compute_credit($store['credit_value'], $step);

		}
		$page['item_count'] = $model_store->getCount(); //获取统计数据
		//		$page['item_count']=$model_store->get_store_count($array);//获取统计数据
		$this->_format_page($page);

		/* 当前位置 */
		$this->_curlocal($this->_get_store_curlocal($cate_id));
		$region_list = $this->_list_region(); //获得地区分类
		$scategorys = $this->_list_scategory(); //获得店铺分类
		$regiondata = array ();
		$region_mod = & m('region');
		$regions = $region_mod->get_list(195);
		$i = 0;
		foreach ($regions as $value) {
			$regiondata[$value["region_id"]] = $value["region_name"];
		}

		$this->assign('regions', $regiondata);
		$this->assign('cate_id', $cate_id);
		$this->assign('scategorys', $scategorys);
		$this->assign('region_list', $region_list);
		$this->assign('page_info', $page);
		/* 配置seo信息 */
		//        $this->_config_seo($this->_get_seo_info('store', $cate_id));

		$this->assign('stores', $stores);
		$this->display('search.store.html');
	}

	function get_scategory() {
		/* 取得店铺分类
			     */
		$scategory_mod = & m('scategory');
		$scategories = $scategory_mod->get_list();

		$tree = & $this->_tree($scategories);

		/* 先根排序*/
		$sorted_scategories = array ();
		$scategory_ids = $tree->getChilds();
		foreach ($scategory_ids as $id) {
			$sorted_scategories[] = array_merge($scategories[$id], array (
				'layer' => $tree->getLayer($id
			)));
		}

		return $data['by_category'] = $sorted_scategories;
	}

	function get_brand() { //商标分类
		$brand_mod = & m('price');
		$by_brands = $brand_mod->get_brand_list();
		return $by_brands;
	}

	function get_region() { //地区分类
		$region_mod = & m('region');
		$region = $region_mod->get_list(195);
		return $region;
	}

	function get_price() { //价格分类
		$price_mod = & m('price');
		$pricelist = $price_mod->get_list();
		return $pricelist;
	}

	function get_total($param = array ()) { //查询数量
		$price_mod = & m('price');
		$total = $price_mod->get_modeltotal($param);
		return $total;
	}

    function get_catetotal($param = array ()) { //查询数量
		$price_mod = & m('price');
		$total = $price_mod->get_catemodeltotal($param);
		return $total;
	}

	function get_goods_total($array = array ()) { //查询商品分类下的商品总数量
		$price_mod = & m('price');
		$total = $price_mod->get_goods_modeltotal($array);
		return $total;
	}

	function get_goods_keywordName($array = array ()) {
		$price_mod = & m('price');
		$array = $price_mod->get_goods_modelKeywordName($array);
		return $array;
	}

	function get_gstore_keywordName($array = array ()) {
		$price_mod = & m('price');
		$array = $price_mod->get_store_modelKeywordName($array);
		return $array;
	}

	function groupbuy() {
		empty ($_GET['state']) && $_GET['state'] = 'on';
		$conditions = '1=1';

		// 排序
		$orders = array (
			'group_id desc' => Lang :: get('select_pls'
		), 'views desc' => Lang :: get('views'),);

		if ($_GET['state'] == 'on') {
			$orders['end_time asc'] = Lang :: get('lefttime');
			$conditions .= ' AND gb.state =' . GROUP_ON . ' AND gb.end_time>' . gmtime();
		}
		elseif ($_GET['state'] == 'end') {
			$conditions .= ' AND (gb.state=' . GROUP_ON . ' OR gb.state=' . GROUP_END . ') AND gb.end_time<=' . gmtime();
		} else {
			$conditions .= $this->_get_query_conditions(array (
				array (//按团购状态搜索
					'field' => 'gb.state',
					'name' => 'state',
					'handler' => 'groupbuy_state_translator',


				)
			));
		}
		$conditions .= $this->_get_query_conditions(array (
			array (//活动名称
				'field' => 'group_name',
				'equal' => 'LIKE',
				'assoc' => 'AND',
				'name' => 'keyword',
				'type' => 'string',


			),


		));
		$page = $this->_get_page(NUM_PER_PAGE); //获取分页信息
		$groupbuy_mod = & m('groupbuy');
		$groupbuy_list = $groupbuy_mod->find(array (
			'conditions' => $conditions,
			'fields' => 'gb.group_name,gb.spec_price,gb.min_quantity,gb.store_id,gb.state,gb.end_time,g.default_image,default_spec,s.store_name',
			'join' => 'belong_store, belong_goods',
			'limit' => $page['limit'],
				'count' => true, //允许统计
	'order' => isset ($_GET['order']
		) && isset ($orders[$_GET['order']]) ? $_GET['order'] : 'group_id desc',));
		if ($ids = array_keys($groupbuy_list)) {
			$quantity = $groupbuy_mod->get_join_quantity($ids);
		}
		foreach ($groupbuy_list as $key => $groupbuy) {
			$groupbuy_list[$key]['quantity'] = empty ($quantity[$key]['quantity']) ? 0 : $quantity[$key]['quantity'];
			$groupbuy['default_image'] || $groupbuy_list[$key]['default_image'] = Conf :: get('default_goods_image');
			$groupbuy['spec_price'] = unserialize($groupbuy['spec_price']);
			$groupbuy_list[$key]['group_price'] = $groupbuy['spec_price'][$groupbuy['default_spec']]['price'];
			$groupbuy['state'] == GROUP_ON && $groupbuy_list[$key]['lefttime'] = lefttime($groupbuy['end_time']);
		}
		$this->assign('state', array (
			'on' => Lang :: get('group_on'
		), 'end' => Lang :: get('group_end'), 'finished' => Lang :: get('group_finished'), 'canceled' => Lang :: get('group_canceled')));
		$this->assign('orders', $orders);
		// 当前位置
		$this->_curlocal(array (
			array (
				'text' => Lang :: get('groupbuy'
			)
		)));
		$this->_config_seo('title', Lang :: get('groupbuy') . ' - ' . Conf :: get('site_title'));
		$page['item_count'] = $groupbuy_mod->getCount(); //获取统计数据
		$this->_format_page($page);
		$this->assign('nav_groupbuy', 1); // 标识当前页面是团购列表，用于设置导航状态
		$this->assign('page_info', $page);
		$this->assign('groupbuy_list', $groupbuy_list);
		$this->assign('recommended_groupbuy', $this->_recommended_groupbuy(2));
		$this->assign('last_join_groupbuy', $this->_last_join_groupbuy(2));
		$this->display('search.groupbuy.html');
	}

	// 推荐团购活动
	function _recommended_groupbuy($_num) {
		$model_groupbuy = & m('groupbuy');
		$data = $model_groupbuy->find(array (
			'join' => 'belong_goods',
		'conditions' => 'gb.recommended=1 AND gb.state=' . GROUP_ON . ' AND gb.end_time>' . gmtime(), 'fields' => 'group_id, goods.default_image, group_name, end_time, spec_price', 'order' => 'group_id DESC', 'limit' => $_num,));
		foreach ($data as $gb_id => $gb_info) {
			$price = current(unserialize($gb_info['spec_price']));
			empty ($gb_info['default_image']) && $data[$gb_id]['default_image'] = Conf :: get('default_goods_image');
			$data[$gb_id]['lefttime'] = lefttime($gb_info['end_time']);
			$data[$gb_id]['price'] = $price['price'];
		}
		return $data;
	}

	// 最新参加的团购
	function _last_join_groupbuy($_num) {
		$model_groupbuy = & m('groupbuy');
		$data = $model_groupbuy->find(array (
			'join' => 'be_join,belong_goods',
			'fields' => 'gb.group_id,gb.group_name,gb.group_id,groupbuy_log.add_time,gb.spec_price,goods.default_image',
			'conditions' => 'groupbuy_log.user_id > 0',
			'order' => 'groupbuy_log.add_time DESC',
			'limit' => $_num,


		));
		foreach ($data as $gb_id => $gb_info) {
			$price = current(unserialize($gb_info['spec_price']));
			empty ($gb_info['default_image']) && $data[$gb_id]['default_image'] = Conf :: get('default_goods_image');
			$data[$gb_id]['price'] = $price['price'];
		}
		return $data;
	}

	/* 取得店铺分类 */
	function _list_scategory() {
		$scategory_mod = & m('scategory');
		$scategories = $scategory_mod->get_list(-1, true);

		import('tree.lib');
		$tree = new Tree();
		$tree->setTree($scategories, 'cate_id', 'parent_id', 'cate_name');
		return $tree->getArrayList(0);
	}

	/* 取得地区分类 */
	function _list_region() {
		$region_mod = & m('region');
		$cate = $region_mod->get_list(195);
		$data = array ();
		foreach ($cate as $key => $value) {
			$cate[$key]['id'] = $value['region_id'];
			$cate[$key]['value'] = $value['region_name'];
		}
		return $cate;
	}

	function _get_goods_curlocal($cate_id) {
		$parents = array ();
		if ($cate_id) {
			$gcategory_mod = & bm('gcategory');
			$parents = $gcategory_mod->get_ancestor($cate_id, true);
		}

		$curlocal = array (
			array (
				'text' => LANG :: get('all_categories'
			),
			'url' => "javascript:dropParam('cate_id')"
		),);
		foreach ($parents as $category) {
			$curlocal[] = array (
				'text' => $category['cate_name'],
				'url' => "javascript:replaceParam('cate_id', '" . $category['cate_id'] . "')"
			);
		}
		unset ($curlocal[count($curlocal) - 1]['url']);

		return $curlocal;
	}

	function _get_store_curlocal($cate_id) {
		$parents = array ();
		if ($cate_id) {
			$scategory_mod = & m('scategory');
			$scategory_mod->get_parents($parents, $cate_id);
		}

		$curlocal = array (
			array (
				'text' => LANG :: get('all_categories'
			),
			'url' => url('app=category&act=store'
		)),);
		foreach ($parents as $category) {
			$curlocal[] = array (
				'text' => $category['cate_name'],
				'url' => url('app=search&act=store&cate_id=' . $category['cate_id']
			));
		}
		unset ($curlocal[count($curlocal) - 1]['url']);
		return $curlocal;
	}

	function _get_brand_curlocal($brand_id) {
		$parents = array ();
		if ($brand_id) {
			$scategory_mod = & m('scategory');
			$scategory_mod->get_parents($parents, $brand_id);
		}

		$curlocal = array (
			array (
				'text' => LANG :: get('all_categories'
			),
			'url' => url('app=category&act=store'
		)),);
		foreach ($parents as $category) {
			$curlocal[] = array (
				'text' => $category['brand_name'],
				'url' => url('app=search&act=goods&brand_id=' . $category['brand_id']
			));
		}
		unset ($curlocal[count($curlocal) - 1]['url']);
		return $curlocal;
	}

	/**
	 * 取得查询参数（有值才返回）
	 *
	 * @return  array(
	 *              'keyword'   => array('aa', 'bb'),
	 *              'cate_id'   => 2,
	 *              'layer'     => 2, // 分类层级
	 *              'brand'     => 'ibm',
	 *              'region_id' => 23,
	 *              'price'     => array('min' => 10, 'max' => 100),
	 *          )
	 */
	function _get_query_param() {
		static $res = null;
		if ($res === null) {
			$res = array ();

			// keyword
			$keyword = isset ($_GET['keyword']) ? trim($_GET['keyword']) : '';
			if ($keyword != '') {
				//$keyword = preg_split("/[\s," . Lang::get('comma') . Lang::get('whitespace') . "]+/", $keyword);
				$tmp = str_replace(array (
					Lang :: get('comma'
				), Lang :: get('whitespace'), ' '), ',', $keyword);
				$keyword = explode(',', $tmp);
				sort($keyword);
				$res['keyword'] = $keyword;
			}

			// cate_id
			if (isset ($_GET['cate_id']) && intval($_GET['cate_id']) > 0) {
				$res['cate_id'] = $cate_id = intval($_GET['cate_id']);
				$gcategory_mod = & bm('gcategory');
				$res['layer'] = $gcategory_mod->get_layer($cate_id, true);
			}

			// brand
			if (isset ($_GET['brand'])) {
				$brand = trim($_GET['brand']);
				$res['brand'] = $brand;
			}

			// region_id
			if (isset ($_GET['region_id']) && intval($_GET['region_id']) > 0) {
				$res['region_id'] = intval($_GET['region_id']);
			}

			// price
			if (isset ($_GET['price'])) {
				$arr = explode('-', $_GET['price']);
				$min = abs(floatval($arr[0]));
				$max = abs(floatval($arr[1]));
				if ($min * $max > 0 && $min > $max) {
					list ($min, $max) = array (
						$max,
						$min
					);
				}

				$res['price'] = array (
					'min' => $min,
					'max' => $max
				);
			}
		}

		return $res;
	}

	/**
	 * 取得过滤条件
	 */
	function _get_filter($param) {
		static $filters = null;
		if ($filters === null) {
			$filters = array ();
			if (isset ($param['keyword'])) {
				$keyword = join(' ', $param['keyword']);
				$filters['keyword'] = array (
					'key' => 'keyword',
					'name' => LANG :: get('keyword'
				), 'value' => $keyword);
			}
			isset ($param['brand']) && $filters['brand'] = array (
				'key' => 'brand',
				'name' => LANG :: get('brand'
			), 'value' => $param['brand']);
			if (isset ($param['region_id'])) {
				// todo 从地区缓存中取
				$region_mod = & m('region');
				$row = $region_mod->get(array (
					'conditions' => $param['region_id'],
					'fields' => 'region_name'
				));
				$filters['region_id'] = array (
					'key' => 'region_id',
					'name' => LANG :: get('region'
				), 'value' => $row['region_name']);
			}
			if (isset ($param['price'])) {
				$min = $param['price']['min'];
				$max = $param['price']['max'];
				if ($min <= 0) {
					$filters['price'] = array (
						'key' => 'price',
						'name' => LANG :: get('price'
					), 'value' => LANG :: get('le') . ' ' . price_format($max));
				}
				elseif ($max <= 0) {
					$filters['price'] = array (
						'key' => 'price',
						'name' => LANG :: get('price'
					), 'value' => LANG :: get('ge') . ' ' . price_format($min));
				} else {
					$filters['price'] = array (
						'key' => 'price',
						'name' => LANG :: get('price'
					), 'value' => price_format($min) . ' - ' . price_format($max));
				}
			}
		}
		return $filters;
	}

	/**
	 * 取得查询条件语句
	 *
	 * @param   array   $param  查询参数（参加函数_get_query_param的返回值说明）
	 * @return  string  where语句
	 */
	function _get_goods_conditions($param) {
		/* 组成查询条件 */
		$conditions = " g.if_show = 1 AND g.closed = 0 AND s.state = 1"; // 上架且没有被禁售，店铺是开启状态,
		if (isset ($param['keyword'])) {
			$conditions .= $this->_get_conditions_by_keyword($param['keyword'], ENABLE_SEARCH_CACHE);
		}
		if (isset ($param['cate_id'])) {
			$conditions .= " AND g.cate_id_{$param['layer']} = '" . $param['cate_id'] . "'";
		}
		if (isset ($param['brand'])) {
			$conditions .= " AND g.brand = '" . $param['brand'] . "'";
		}
		if (isset ($param['region_id'])) {
			$conditions .= " AND s.region_id = '" . $param['region_id'] . "'";
		}
		if (isset ($param['price'])) {
			$min = $param['price']['min'];
			$max = $param['price']['max'];
			$min > 0 && $conditions .= " AND g.price >= '$min'";
			$max > 0 && $conditions .= " AND g.price <= '$max'";
		}

		return $conditions;
	}

	/**
	 * 根据查询条件取得分组统计信息
	 *
	 * @param   array   $param  查询参数（参加函数_get_query_param的返回值说明）
	 * @param   bool    $cached 是否缓存
	 * @return  array(
	 *              'total_count' => 10,
	 *              'by_category' => array(id => array('cate_id' => 1, 'cate_name' => 'haha', 'count' => 10))
	 *              'by_brand'    => array(array('brand' => brand, 'count' => count))
	 *              'by_region'   => array(array('region_id' => region_id, 'region_name' => region_name, 'count' => count))
	 *              'by_price'    => array(array('min' => 10, 'max' => 50, 'count' => 10))
	 *          )
		   */
	function _get_group_by_info($param = array (), $cached) {
		$nums = count($param);
		$data['by_category'] = $this->get_scategory();
		$data['by_brand'] = $this->get_brand();
		/* 按地区统计 */
		$data['by_region'] = $this->get_region();
		$data['by_price'] = $this->get_price();
		if ($nums == 0) { //菜单
			//查询总数量
			$data['total_count'] = $this->get_total();
		} else {
			if(!empty($param['cate_id'])){
                $data['total_count'] = $this->get_catetotal($param);
			}else{
				$data['total_count'] = $this->get_total($param);
			}
		}
		return $data;
	}

	function _get_goods_group_by_info($array = array ()) {
		$data['by_category'] = $this->get_scategory();
		$data['by_brand'] = $this->get_brand();
		/* 按地区统计 */
		$data['by_region'] = $this->get_region();
		$data['by_price'] = $this->get_price();
		$data['total_count'] = $this->get_goods_total($array);

		return $data;
	}

	function _get_keyword_group_by_info($array = array ()) {
		$data = $this->get_goods_keywordName($array);
		return $data;
	}

	function _get_store_group_by_info($array = array ()) {
		$data = $this->get_gstore_keywordName($array);
		return $data;
	}

	/* 构造并返回树 */
	function & _tree($scategories) {
		import('tree.lib');
		$tree = new Tree();
		$tree->setTree($scategories, 'cate_id', 'parent_id', 'cate_name');
		return $tree;
	}

	/**
	 * 根据关键词取得查询条件（可能是like，也可能是in）
	 *
	 * @param   array       $keyword    关键词
	 * @param   bool        $cached     是否缓存
	 * @return  string      " AND (0)"
	 *                      " AND (goods_name LIKE '%a%' AND goods_name LIKE '%b%')"
	 *                      " AND (goods_id IN (1,2,3))"
	 */
	function _get_conditions_by_keyword($keyword, $cached) {
		$conditions = false;

		//        if ($cached)
		//        {
		//            $cache_server =& cache_server();
		//            $key1 = 'query_conditions_of_keyword_' . join("\t", $keyword);
		//            $conditions = $cache_server->get($key1);
		//        }

		//        if ($conditions === false)
		//        {
		/* 组成查询条件 */
		$conditions = array ();
		foreach ($keyword as $word) {
			$conditions[] = "g.goods_name LIKE '%{$word}%'";
		}
		$conditions = join(' AND ', $conditions);

		/* 取得满足条件的商品数 */
		$goods_mod = & m('goods');
		$sql = "SELECT COUNT(*) FROM {$goods_mod->table} g WHERE " . $conditions;
		$current_count = $goods_mod->getOne($sql);
		if ($current_count > 0) {
			if ($current_count < MAX_ID_NUM_OF_IN) {
				/* 取得商品表记录总数 */
				$cache_server = & cache_server();
				$key2 = 'record_count_of_goods';
				$total_count = $cache_server->get($key2);
				if ($total_count === false) {
					$sql = "SELECT COUNT(*) FROM {$goods_mod->table}";
					$total_count = $goods_mod->getOne($sql);
					$cache_server->set($key2, $total_count, SEARCH_CACHE_TTL);
				}

				/* 不满足条件，返回like */
				if (($current_count / $total_count) < MAX_HIT_RATE) {
					/* 取得满足条件的商品id */
					$sql = "SELECT goods_id FROM {$goods_mod->table} g WHERE " . $conditions;
					$ids = $goods_mod->getCol($sql);
					$conditions = 'g.goods_id' . db_create_in($ids);
				}
			}
		} else {
			/* 没有满足条件的记录，返回0 */
			$conditions = "0";
		}

		//            if ($cached)
		//            {
		//                $cache_server->set($key1, $conditions, SEARCH_CACHE_TTL);
		//            }
		//        }
		return ' AND (' . $conditions . ')';
	}

	/* 商品排序方式 */
	function _get_orders() {
		return array (
			'' => Lang :: get('select_pls'
		), 'sales desc' => Lang :: get('sales_desc'), 'credit_value desc' => Lang :: get('credit_value_desc'), 'price asc' => Lang :: get('price_asc'), 'price desc' => Lang :: get('price_desc'), 'views desc' => Lang :: get('views_desc'), 'add_time desc' => Lang :: get('add_time_desc'),);
	}

	function _get_seo_info($type, $cate_id) {
		$seo_info = array (
			'title' => '',
			'keywords' => '',
			'description' => ''
		);
		$parents = array (); // 所有父级分类包括本身
		switch ($type) {
			case 'goods' :
				if ($cate_id) {
					$gcategory_mod = & bm('gcategory');
					$parents = $gcategory_mod->get_ancestor($cate_id, true);
					$parents = array_reverse($parents);
				}
				$filters = $this->_get_filter($this->_get_query_param());
				foreach ($filters as $k => $v) {
					$seo_info['keywords'] .= $v['value'] . ',';
				}
				break;
			case 'store' :
				if ($cate_id) {
					$scategory_mod = & m('scategory');
					$scategory_mod->get_parents($parents, $cate_id);
					$parents = array_reverse($parents);
				}
		}

		foreach ($parents as $key => $cate) {
			$seo_info['title'] .= $cate['cate_name'] . ' - ';
			$seo_info['keywords'] .= $cate['cate_name'] . ',';
			if ($cate_id == $cate['cate_id']) {
				$seo_info['description'] = $cate['cate_name'] . ' ';
			}
		}
		$seo_info['title'] .= Lang :: get('searched_' . $type) . ' - ' . Conf :: get('site_title');
		$seo_info['keywords'] .= Conf :: get('site_title');
		$seo_info['description'] .= Conf :: get('site_title');
		return $seo_info;
	}
}
?>
